package com.ruoyi.web.controller.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.NumberChineseFormatter;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.redis.QueueUtils;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.system.domain.bo.StockListBo;
import com.ruoyi.system.domain.vo.StockListVo;
import com.ruoyi.system.service.IStockListService;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.web.controller.common.MatchUtil.getInputMsg;
import static com.ruoyi.web.controller.common.MatchUtil.unitToChinese;
import static com.ruoyi.web.controller.common.RobotConstant.*;
import static com.ruoyi.web.controller.common.RobotFeatureEnum.*;

@Component
public class ApiUtil {
    private static IStockListService stockListService;

    public ApiUtil(IStockListService stockListService) {
        ApiUtil.stockListService = stockListService;
    }

    public static String getSimpleTalk(RobotFeatureEnum type) {
        String body = HttpRequest.get(TIAN_API + type.codeType() + TIAN_PARAM + TIAN_KEY)
            .timeout(20000)
            .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if ((Integer) jsonObject.get("code") == 250) {
            return CALL_FAIL_PARAM;
        }
        if ((Integer) jsonObject.get("code") != 200) {
            return CALL_FAIL;
        }
        List<TianEntity> backTxt = JSON.parseArray(jsonObject.getString("newslist"), TianEntity.class);
        if (CollUtil.isEmpty(backTxt)) {
            return CALL_EMPTY;
        }
        TianEntity tianEntity = backTxt.get(0);
        StringBuffer sb = new StringBuffer();
        if (StringUtils.isNotBlank(tianEntity.getTitle())) {
            sb.append("标题：" + tianEntity.getTitle() + "  \n");
        }
        sb.append(tianEntity.getContent());
        return sb.toString();
    }

    public static String getCangShiTalk(RobotFeatureEnum type, String inputString) {
//        Map<String, Object> param = new HashMap<>(8);
        // 藏字内容，2-8个字
//        param.put("word", inputString);
        // 诗句格式，0五言诗[默认]、1七言诗
//        param.put("len", RandomUtil.randomInt(0, 2));
//        // 藏头位置，1藏头[默认]、2藏尾、3藏中、4递增、5递减
//        param.put("type", RandomUtil.randomInt(1, 6));
//        // 押韵类型，1双句一压[默认]、2双句押韵、3一三四押
//        param.put("pat", RandomUtil.randomInt(1, 4));
//        String body = HttpRequest.get(TIAN_API + type.codeType() + TIAN_PARAM + TIAN_KEY)
//            .form(param)
//            .timeout(20000)
//            .execute().body();
        String body = HttpRequest.get("http://api.tianapi.com/cangtoushi/index?key=bf777026dcb57cb8afd2b15936410c3f&word="+inputString+"&len="+RandomUtil.randomInt(0, 2)+"&type="+RandomUtil.randomInt(1, 6)+"&pat="+RandomUtil.randomInt(1, 4)+"")
            .timeout(20000)
            .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if ((Integer) jsonObject.get("code") == 250) {
            return CALL_FAIL_PARAM;
        }
        if ((Integer) jsonObject.get("code") != 200) {
            return CALL_FAIL;
        }
        List<TianEntity> backTxt = JSON.parseArray(jsonObject.getString("newslist"), TianEntity.class);
        if (CollUtil.isEmpty(backTxt)) {
            return CALL_EMPTY;
        }
        StringBuffer sb = new StringBuffer();
        sb.append("  \n");
        sb.append("藏字内容:" + inputString + "  \n");
        sb.append("  \n");
        for (int i = 0; i < backTxt.size(); i++) {
            sb.append("第"+ NumberChineseFormatter.format((double) (i+1),false,false)+"首诗:");
            sb.append(backTxt.get(i).getList() + "  \n");
            sb.append("  \n");
        }
        sb.append("你找到藏在哪了吗");
        return sb.toString();
    }

    public static String getHuangLiTalk(RobotFeatureEnum type, String inputString) {
        String body = HttpRequest.get("http://api.tianapi.com/lunar/index?key=bf777026dcb57cb8afd2b15936410c3f&date="+inputString)
            .timeout(20000)
            .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if ((Integer) jsonObject.get("code") == 250) {
            return CALL_FAIL_PARAM;
        }
        if ((Integer) jsonObject.get("code") != 200) {
            return CALL_FAIL;
        }
        List<TianHuangLiEntity> backTxt = JSON.parseArray(jsonObject.getString("newslist"), TianHuangLiEntity.class);
        if (CollUtil.isEmpty(backTxt)) {
            return CALL_EMPTY;
        }
        TianHuangLiEntity tianEntity = backTxt.get(0);
        StringBuffer sb = new StringBuffer();
        sb.append("  \n");
        sb.append(inputString);
        sb.append("  \n");
        if (StringUtils.isNotBlank(tianEntity.getFestival())) {
            sb.append(tianEntity.getFestival());
            sb.append("  \n");
        }
        sb.append("农历  "+ tianEntity.getLubarmonth()+tianEntity.getLunarday());
        sb.append("  \n");
        sb.append(tianEntity.getTiangandizhiyear()+"年");
        sb.append("  " + tianEntity.getShengxiao());
        sb.append("  \n");
        sb.append(tianEntity.getTiangandizhimonth()+"月");
        sb.append(tianEntity.getTiangandizhiday()+"日");
        sb.append("  \n");
        if (StringUtils.isNotBlank(tianEntity.getLunar_festival())) {
            sb.append(tianEntity.getLunar_festival());
            sb.append("  \n");
        }
        sb.append(tianEntity.getLmonthname());
        sb.append("  \n");
        if (StringUtils.isNotBlank(tianEntity.getJieqi())) {
            sb.append("节气：" + tianEntity.getJieqi() + "  \n");
        }
        sb.append("神位：" +tianEntity.getShenwei());
        sb.append("  \n");
        sb.append("冲煞：" +tianEntity.getChongsha());
        sb.append("  \n");
        sb.append("岁煞：" +tianEntity.getSuisha());
        sb.append("  \n");
        sb.append("宜：" +tianEntity.getFitness());
        sb.append("  \n");
        sb.append("忌："+tianEntity.getTaboo());
        sb.append("  \n");
        return sb.toString();
    }

    public static String getComplexTalk(RobotFeatureEnum type,WxRecMessage message) {
        String body = HttpRequest.get(TIAN_API + type.codeType() + TIAN_PARAM + TIAN_KEY)
            .timeout(20000)
            .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if ((Integer) jsonObject.get("code") == 250) {
            return CALL_FAIL_PARAM;
        }
        if ((Integer) jsonObject.get("code") != 200) {
            return CALL_FAIL;
        }
        List<TianEntity> backTxt = JSON.parseArray(jsonObject.getString("newslist"), TianEntity.class);
        if (CollUtil.isEmpty(backTxt)) {
            return CALL_EMPTY;
        }
        TianEntity tianEntity = backTxt.get(0);
        tianEntity.setRoomTask(type.codeName());
        tianEntity.setRobot_wxid(message.getRobot_wxid());
        tianEntity.setTo_wxid(message.getFrom_wxid());
        if (type == SLOGAN) {
            tianEntity.setQuest(tianEntity.getContent());
            tianEntity.setResult(tianEntity.getAnswer());
        }else if (type == PROVERB){
            tianEntity.setQuest(tianEntity.getFront());
            tianEntity.setResult(StrUtil.subBefore(tianEntity.getBehind(),"。 ",true));
        }else if (type == ZIMI){
            tianEntity.setQuest(tianEntity.getContent());
            tianEntity.setResult(tianEntity.getAnswer());
        }
        StringBuffer sb = new StringBuffer();
        sb.append("【"+type.codeName()+"】");
        sb.append(" \n");
        sb.append("      游戏开始咯! 限时"+TALK_EXPIRATION+unitToChinese(TALK_UNIT) +"仔细看哦，体现手速的时候到了!");
        sb.append(" \n");
        sb.append(" \n");
        sb.append("本次的问题是：");
        sb.append(" \n");
        sb.append(tianEntity.getQuest());
        RedisUtils.setCacheObject(ROBOT_PREFIX+message.getFrom_wxid(),tianEntity, Duration.ofSeconds(TALK_EXPIRATION));
        QueueUtils.addDelayedQueueObject(DELAYED_QUEUE_WENDA,tianEntity,TALK_EXPIRATION, TALK_UNIT);
        return sb.toString();
    }

    public static String getFreeSimpleTalk(RobotFeatureEnum type) {
        String body = HttpRequest.get(FREE_JOKER_API + RandomUtil.randomInt(1, 4950))
            .timeout(20000)
            .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if ((Integer) jsonObject.get("code") == 250) {
            return CALL_FAIL_PARAM;
        }
        if ((Integer) jsonObject.get("code") != 200) {
            return CALL_FAIL;
        }
        List<TianEntity> backTxt = JSON.parseArray(jsonObject.getString("data"), TianEntity.class);
        if (CollUtil.isEmpty(backTxt)) {
            return CALL_EMPTY;
        }
        TianEntity tianEntity = backTxt.get(0);
        StringBuffer sb = new StringBuffer();
        if (StringUtils.isNotBlank(tianEntity.getTitle())) {
            sb.append("标题：" + tianEntity.getTitle() + "  \n");
        }
        sb.append("      ");
        sb.append(tianEntity.getContent());
        return sb.toString();
    }

    public static String getTuLingTalk(WxRecMessage message) {
        TuLingMsg msg = new TuLingMsg();
        msg.setInfo(getInputMsg(message.getMsg()));
        msg.setUserid(message.getFinal_from_wxid());
        String s = JSONObject.toJSONString(msg);
        String body = HttpRequest.post(SEND_TULING_URL)
            .header("Content-type", "application/json;charset=utf-8")
            .body(s)
            .timeout(20000)
            .execute().body();
        System.out.println("TULING_body = " + body);
        TuLingMsg tuLingMsg = JSONObject.parseObject(body, TuLingMsg.class);
        return tuLingMsg.getText();
    }

    public static String getOwnThinkTalk(WxRecMessage message) {
        String body = HttpRequest.get(SEND_OWNTHINK_URL + message.getFinal_from_wxid() +"&spoken="+ getInputMsg(message.getMsg()))
            .timeout(20000)
            .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(body);
        if (!StrUtil.equals(jsonObject.get("message").toString(),"success")) {
            return CALL_FAIL_PARAM;
        }
        String s = jsonObject.getJSONObject("data").getJSONObject("info").get("text").toString();
        return s;
    }

    public static void sendWenDaMsg(TianEntity entity){
        Map<String,Object> map = new HashMap<>();
        map.put("success", Boolean.TRUE);
        map.put("robot_wxid", entity.getRobot_wxid());
        map.put("to_wxid", entity.getTo_wxid());
        map.put("event", "SendTextMsg");
        StringBuilder sb = new StringBuilder();
        sb.append(TALK_EXPIRATION+unitToChinese(TALK_UNIT)+"过去了，没人回答出来哦，现在揭晓，答案是");
        sb.append(" \n");
        sb.append(entity.getResult());
        if (StrUtil.isNotBlank(entity.getReason())) {
            sb.append("。原因是：");
            sb.append(entity.getReason());
            sb.append(" \n");
        }
        map.put("msg", sb.toString());
        String s1 = JSON.toJSONString(map, SerializerFeature.BrowserCompatible);
        HttpRequest.post(SEND_ROBOT_URL)
            .header("Content-type","application/json;charset=utf-8")
            .body(s1)
            .timeout(20000)
            .execute().body();
    }


    public static String getRobotMenu(){
        Map<String, RobotFeatureEnum> map = toMap();
        StringBuilder sb = new StringBuilder();
        sb.append("******"+ROBOT_NAME+"服务平台"+"******");
        sb.append(" \n");
        for (Map.Entry<String, RobotFeatureEnum> enumEntry : map.entrySet()) {
            if (StrUtil.equals("sexy_pic",enumEntry.getValue().codeType())) {
                continue;
            }
            sb.append(enumEntry.getValue().codeName()+"|" + "@"+ROBOT_NAME + " " +enumEntry.getValue().codeName());
            sb.append(" \n");
        }
        sb.append("******欢迎使用，玩得愉快"+"******");
        return sb.toString();
    }


    public static String getStockPriceInfo(String inputMsg) {
        boolean numberFlag = StringUtils.isNumeric(inputMsg.substring(0,1));
        StockListBo stockListBo = new StockListBo();
        List<StockListVo> stockListVos ;
        boolean queryFlag =inputMsg.substring(0,1).matches("^[a-zA-Z]*");
        String queryCode = "";
        StockListVo stockListVo = new StockListVo();
        if (queryFlag) {
            queryCode = inputMsg;
        } else {
            if (numberFlag) {
                stockListBo.setStockCode(inputMsg);
                stockListVos = stockListService.queryList(stockListBo);
            } else {
                stockListBo.setStockName(inputMsg);
                stockListVos = stockListService.queryList(stockListBo);
            }
            if (CollUtil.isEmpty(stockListVos)) {
                return "查询不到该股票"+inputMsg;
            }
            if (stockListVos.size() > 1) {
                return "暂时只支持查询一支股票，建议精确查找";
            }
            stockListVo = stockListVos.get(0);
            queryCode = stockListVo.getQueryStockCode();
        }

        String body = HttpRequest.get(SEND_TENCENT_STOCK + queryCode)
            .timeout(20000)
            .execute().body();
        List<String> split = StrUtil.split(body, "~");
        if (split.size() < 2) {
            return "接口调用失败，找不到结果" +queryCode;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("\n");
        sb.append("股票: "+split.get(1));
        sb.append("\n");
        sb.append("代码: "+split.get(2));
        sb.append("\n");
        sb.append("板块: "+ Optional.ofNullable(stockListVo.getStockPlate()).orElse(queryCode.substring(0,2)));
        sb.append("\n");
        sb.append("当前价格: "+split.get(3));
        sb.append("\n");
        sb.append("昨收: "+split.get(4));
        sb.append("\n");
        sb.append("今开: "+split.get(5));
        sb.append("\n");
        sb.append("成交量（手）: "+split.get(6));
        sb.append("\n");
        sb.append("买一: "+split.get(9) + (queryFlag ? "":"元"));
        sb.append("\n");
        sb.append("买一量（手）: "+split.get(10));
        sb.append("\n");
        sb.append("卖一: "+split.get(19) + (queryFlag ? "":"元"));
        sb.append("\n");
        sb.append("卖一量: "+split.get(20));
        sb.append("\n");
        sb.append("时间: "+ (queryFlag ?split.get(30):DateUtil.format(DateUtil.parse(split.get(30),"yyyyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss")));
        sb.append("\n");
        sb.append("涨跌: "+split.get(31) + (queryFlag ? "":"元"));
        sb.append("\n");
        sb.append("涨跌%: "+split.get(32));
        sb.append("\n");
        sb.append("最高: "+split.get(33));
        sb.append("\n");
        sb.append("最低: "+split.get(34));
        sb.append("\n");
        sb.append("价格/成交量（手）/成交额: "+split.get(35));
        sb.append("\n");
        sb.append("成交量（手）: "+split.get(36));
        sb.append("\n");
        sb.append("成交额（万）: "+split.get(37));
        sb.append("\n");
        sb.append("换手率: "+split.get(38) + "%");
        sb.append("\n");
        sb.append("市盈率: "+split.get(39));
        sb.append("\n");
        sb.append("最高: "+split.get(41));
        sb.append("\n");
        sb.append("最低: "+split.get(42));
        sb.append("\n");
        sb.append("振幅: "+split.get(43));
        sb.append("\n");
        sb.append("流通市值: "+split.get(44));
        sb.append("\n");
        sb.append("总市值: "+split.get(45));
        sb.append("\n");
        sb.append("市净率: "+split.get(46));
        sb.append("\n");
        sb.append("涨停价: "+split.get(47));
        sb.append("\n");
        sb.append(" 跌停价: "+split.get(48));
        sb.append("\n");
        return sb.toString();
    }

    public static String getZhiShuInfo(){
        String body = HttpRequest.get(SEND_TENCENT_STOCK + A_ZHI_SHU.stream().collect(Collectors.joining(",")))
            .timeout(20000)
            .execute().body();
        List<String> splitList = StrUtil.split(body, ";");
        if (splitList.size() < 2) {
            return "接口调用失败，找不到结果" ;
        }
        StringBuilder sb = new StringBuilder();
        for (String splits : splitList) {
            List<String> split = StrUtil.split(splits, "~");
            if (split.size() < 2) {
                continue;
            }
            sb.append("\n");
            sb.append("股票: "+split.get(1));
            sb.append("\n");
            sb.append("代码: "+split.get(2));
            sb.append("\n");
            sb.append("当前价格: "+split.get(3));
            sb.append("\n");
            sb.append("昨收: "+split.get(4));
            sb.append("\n");
            sb.append("今开: "+split.get(5));
            sb.append("\n");
            sb.append("成交量（手）: "+split.get(6));
            sb.append("\n");
            sb.append("时间: "+ DateUtil.format(DateUtil.parse(split.get(30),"yyyyMMddHHmmss"), "yyyy-MM-dd HH:mm:ss"));
            sb.append("\n");
            sb.append("涨跌: "+split.get(31) + "元");
            sb.append("\n");
            sb.append("涨跌%: "+split.get(32));
            sb.append("\n");
            sb.append("成交量（手）: "+split.get(36));
            sb.append("\n");
            sb.append("成交额（万）: "+split.get(37));
            sb.append("\n");
            sb.append("换手率: "+split.get(38) + "%");
            sb.append("\n");
            sb.append("最高: "+split.get(41));
            sb.append("\n");
            sb.append("最低: "+split.get(42));
            sb.append("\n");
            sb.append("振幅: "+split.get(43));
            sb.append("\n");
        }
        return sb.toString();
    }
}
